package com.huazai.yangge.interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 停止线程的3中方法，    线程终止不是立刻停止，而是设置了一个标志位
 * @author huazai
 * @date 2024/2/23
 */
public class InterruptDemo {
    static volatile boolean isStop = false;
    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);
    public static void main(String[] args) throws InterruptedException {
        //new Thread(() ->
        //{
        //    while (true) {
        //        if (isStop) {
        //            System.out.println(Thread.currentThread().getName() + " stop");
        //            break;
        //        }
        //    }
        //}).start();
        //
        //TimeUnit.MILLISECONDS.sleep(200);
        //
        //new Thread(() ->
        //{
        //    isStop = true;
        //}).start();
        //new Thread(() ->
        //{
        //    while (true) {
        //        if (atomicBoolean.get()) {
        //            System.out.println(Thread.currentThread().getName() + " stop");
        //            break;
        //        }
        //    }
        //}).start();
        //
        //TimeUnit.MILLISECONDS.sleep(200);
        //
        //new Thread(() ->
        //{
        //    atomicBoolean.set(true);
        //}).start();

        final Thread thread = new Thread(() ->
        {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println(Thread.currentThread().getName() + " stop");
                    break;
                }
                System.out.println(" adfadf");
            }
        }, "t1");
        thread.start();

        TimeUnit.MILLISECONDS.sleep(200);

        new Thread(() ->
        {
            thread.interrupt();
        }, "t2").start();
    }
}


